package com.quan.hr.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.quan.commons.core.MyBaseServiceImpl;
import com.quan.commons.interceptor.LoginUserInterceptor;
import com.quan.commons.utils.PageUtils;
import com.quan.hr.commons.export.HrDeptImportVo;
import com.quan.hr.commons.vo.HrDeptVo;
import com.quan.hr.entity.HrDept;
import com.quan.hr.mapper.HrDeptMapper;
import com.quan.hr.service.HrDeptService;
import com.quan.system.commons.vo.SysUserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
@DS("master")
public class HrDeptServiceImpl extends MyBaseServiceImpl<HrDeptMapper, HrDept> implements HrDeptService {

    @Autowired
    private HrDeptMapper mapper;

    @Override
    public boolean updateById(HrDeptVo vo) {
        final SysUserVo user = LoginUserInterceptor.loginUser.get();
        vo.setUname(null != user.getEmpName() ? user.getEmpName() : user.getUsername());
        return super.updateById(vo);
    }

    @Override
    public HrDeptVo getInfo(Long id) {
        final HrDept depart = super.getById(id);

        HrDeptVo bean = new HrDeptVo();
        BeanUtils.copyProperties(depart, bean);

        // 反推获取节点的父路径
        bean.setCascaderDeptPathVals(this.findPath(bean.getId()));

        return bean;
    }

    @Override
    public List<HrDeptVo> queryList(PageUtils pageUtils, HrDeptVo vo) {
        QueryWrapper<HrDept> queryWrapper = new QueryWrapper<HrDept>(vo);

        List<HrDept> list = super.list(pageUtils, queryWrapper);
        List<HrDeptVo> collect = list.stream().map(item -> {
            HrDeptVo bean = new HrDeptVo();
            BeanUtils.copyProperties(item, bean);
            return bean;
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    public PageUtils queryPage(PageUtils pageUtils, HrDeptVo vo) {
        QueryWrapper<HrDept> queryWrapper = new QueryWrapper<HrDept>(vo);

        if (StringUtils.isNotBlank(vo.getKeyword())) {
            queryWrapper.and(w -> {
                w.like("name", vo.getKeyword());
            });
        }

        final IPage<HrDept> page = super.selectPage(pageUtils, queryWrapper);

        PageUtils ps = new PageUtils(page);

        final List<HrDept> records = page.getRecords();

        final List<HrDept> collect = records.stream().map((item) -> {
            HrDeptVo bean = new HrDeptVo();
            BeanUtils.copyProperties(item, bean);
            return bean;
        }).collect(Collectors.toList());

        ps.setRecords(collect);
        return ps;
    }

    @Override
    public List<HrDeptVo> listWithTree() {

        final List<HrDept> list = super.list();

        // 获取一级分类
        final List<HrDeptVo> collect = list.stream()
                .filter(category -> category.getPid() == null)
                .map(item -> {
                    HrDeptVo bean = new HrDeptVo();
                    BeanUtils.copyProperties(item, bean);

                    // 获取子分类
                    bean.setChildren(getChildrens(bean, list));

                    return bean;
                }).sorted((menu, menu2) -> {
                    //2、菜单的排序
                    return (menu.getSort() == null ? 0 : menu.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                }).collect(Collectors.toList());

        return collect;
    }

    //递归查找所有菜单的子菜单
    private List<HrDept> getChildrens(HrDeptVo root, List<HrDept> all) {

        List<HrDept> children = all.stream().filter(categoryEntity -> {
            return null != categoryEntity.getPid() && categoryEntity.getPid().equals(root.getId());
        }).map(item -> {
            HrDeptVo bean = new HrDeptVo();
            BeanUtils.copyProperties(item, bean);
            //1、找到子菜单(递归)
            bean.setChildren(getChildrens(bean, all));
            return bean;
        }).sorted((menu, menu2) -> {
            //2、菜单的排序
            return (menu.getSort() == null ? 0 : menu.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

    /**
     * 保存导入的excel数据
     * @param list
     * @return
     */
    @Override
    public boolean saveImportData(List<HrDeptImportVo> list) {
        final List<HrDept> entitys = list.stream().map(item -> {
            HrDeptVo vo = new HrDeptVo();
            vo.setId(Long.parseLong(item.getDeptId()));
            vo.setName(item.getDeptName());
            vo.setPid(Long.parseLong(item.getDeptPid()));
            return vo;
        }).collect(Collectors.toList());


        // 获取一级分类
        entitys.stream()
                .filter(category -> category.getPid() == 0 || category.getPid() == null)
                .map(item -> {
                    HrDeptVo bean = new HrDeptVo();
                    BeanUtils.copyProperties(item, bean);

                    log.info("部门：{}, {}, {}", item.getId(), item.getName(), item.getPid());
                    HrDept entity = new HrDept();
                    entity.setName(item.getName());
                    entity.setSort(99);
                    super.save(entity);

                    // 获取子分类
                    bean.setChildren(getChildrensImportData(bean, entitys, entity.getId()));

                    return bean;
                }).sorted((menu, menu2) -> {
            //2、菜单的排序
            return (menu.getSort() == null ? 0 : menu.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return false;
    }

    //递归查找所有菜单的子菜单
    private List<HrDept> getChildrensImportData(HrDeptVo root, List<HrDept> all, Long rootId) {

        List<HrDept> children = all.stream().filter(categoryEntity -> {
            return null != categoryEntity.getPid() && categoryEntity.getPid().equals(root.getId());
        }).map(item -> {
            HrDeptVo bean = new HrDeptVo();
            BeanUtils.copyProperties(item, bean);

            log.info("部门：{}, {}, {}", item.getId(), item.getName(), item.getPid());
            HrDept entity = new HrDept();
            entity.setPid(rootId);
            entity.setName(item.getName());
            entity.setSort(99);
            super.save(entity);


            //1、找到子菜单(递归)
            bean.setChildren(getChildrensImportData(bean, all, entity.getId()));
            return bean;
        }).sorted((menu, menu2) -> {
            //2、菜单的排序
            return (menu.getSort() == null ? 0 : menu.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

    /**
     * 根据子节点找到完整的父节点路径
     * @param id
     * @return
     */
    @Override
    public Long[] findPath(Long id) {

        List<Long> paths = new ArrayList<>();

        //递归查询是否还有父节点
        List<Long> parentPath = findParentPath(id, paths);

        //进行一个逆序排列
        Collections.reverse(parentPath);

        return (Long[]) parentPath.toArray(new Long[parentPath.size()]);
    }

    private List<Long> findParentPath(Long id, List<Long> paths) {
        //1、收集当前节点id
        paths.add(id);

        //根据当前分类id查询信息
        HrDept byId = this.getById(id);
        //如果当前不是父分类
        if (null != byId && byId.getPid() != null) {
            findParentPath(byId.getPid(), paths);
        }
        return paths;
    }
}